package com.xlf.wheretogo.service;

import com.xlf.wheretogo.entity.Location;
import com.xlf.wheretogo.mapper.LocationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LocationService {

    @Autowired
    LocationMapper locationMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public Location selectLocationByID(int id) {
        String key = "location_" + id;
        ValueOperations<String, Location> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            long start = System.currentTimeMillis();
            Location location = operations.get(key);
            System.out.println("==========从缓存中获得数据=========");
            System.out.println(location.getLocation_name());
            System.out.println("==============================");
            long end = System.currentTimeMillis();
            System.out.println("查询redis花费的时间是:" + (end - start) + "s");
            return location;
        } else {
            long start = System.currentTimeMillis();
            Location location = locationMapper.selectLocationByID(id);
            if (null != location) {
                System.out.println("==========从数据表中获得数据=========");
                System.out.println(location.getLocation_name());
                System.out.println("==============================");
                // 写入缓存
                operations.set(key, location, 5, TimeUnit.HOURS);
            } else {
                System.out.println("==========数据不存在=========");
                return null;
            }
            long end = System.currentTimeMillis();
            System.out.println("查询mysql花费的时间是:" + (end - start) + "s");
            return location;
        }
    }

    public int deleteLocationByID(int id) {
        int result = locationMapper.deleteLocationByID(id);
        String key = "location_" + id;
        if (result != 0) {
            boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey) {
                redisTemplate.delete(key);
                System.out.println("删除了缓存中的key:" + key);
            }
        }
        return result;
    }

    public int addLocation(Location location) {
        System.out.println("预插入数据：" + location);
        return locationMapper.addLocation(location);
    }
}
